import {messages} from "share/common";
/**
 * Created by 13576 on 2017/10/20.
 */
import React from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import { Spin, Popover, Button, Table, message, Icon, Badge, Row, Col, Input, Affix } from 'antd';

import budgetJournalService from 'containers/budget/budget-journal-re-check/budget-journal-re-check.service'
import "styles/budget/budget-journal-re-check/budget-journal-re-check-detail.scss"

class BudgetJournalReCheckDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      passLoading: false,
      rejectLoading: false,
      data: [],
      params: {},
      spinLoading: true,
      headerAndListData: {},
      totalAmount: 0,
      pageSize: 10,
      page: 0,
      total: 0,
      pagination: {
        current: 0,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      organization: {},
      fileList: [],
      infoData: {},
      columns: [
        {
          title: messages('budget.key85'/*公司*/), dataIndex: 'companyName', width: '8%',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('budget.key86'/*部门*/), dataIndex: 'departmentName', width: '8%',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('budget.key103'/*申请人*/), dataIndex: 'employeeName',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('budget.key88'/*预算项目*/), dataIndex: 'itemName', width: '16%',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('budget.key89'/*期间*/), dataIndex: 'periodName', width: '6%'
        },
        {
          title: messages('budget.key90'/*预算季度*/), dataIndex: 'periodQuarterName', width: '6%'
        },
        {
          title: messages('budget.key91'/*预算年度*/), dataIndex: 'periodYear', width: '8%'
        },
        {
          title: messages('budget.key165')/*半年度*/, dataIndex: 'periodSemiannualName',
        },
        {
          title: messages('budget.key92'/*币种*/), dataIndex: 'currency', width: '8%'
        },
        {
          title: messages('budget.key93'/*汇率*/), dataIndex: 'rate', width: '8%',
        },
        {
          title: messages('budget.key94'/*金额*/), dataIndex: 'amount',
          render: value => <Popover content={this.filterMoney(value)}>{this.filterMoney(value)}</Popover>
        },
        {
          title: messages('budget.key95'/*本币金额*/), dataIndex: 'functionalAmount',
          render: value => <Popover content={this.filterMoney(value)}>{this.filterMoney(value)}</Popover>
        },
        {
          title: messages('budget.key96'/*数量*/), dataIndex: 'quantity', with: '8%'
        },
        {
          title: messages('budget.key97'/*行备注*/), dataIndex: 'remark',
          render: value => <Popover content={value}>{value}</Popover>
        },
      ],
      budgetJournalDetailReCheckPage: menuRoute.getRouteItem('budget-journal-re-check'), //预算日记账复核
    };
  }

  componentWillMount = () => {
    this.getToleAmount();
    this.getBudgetJournalHead();
    this.getBudgetJournalLine();

  }

  //获取日记账总金额
  getToleAmount() {
    let infoDate = this.state.infoDate;
    budgetJournalService.getTotalCurrencyAmount(this.props.params.journalCode).then((response) => {
      let totalAmount = response.data;
      this.setState({ infoDate, totalAmount });
    })
  }

  //获取日记账头
  getBudgetJournalHead() {
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalHeaderDetil(budgetCode).then((request) => {
      this.getDimensionByStructureId(request.data.structureId);
      let headerData = request.data;
      headerData.attachmentOID.map((item) => {
        this.getFileByAttachmentOID(item);
      })
      let headerAndListData = {
        dto: request.data,
        list: [],
      }
      this.setState({
        headerData: headerData,
        headerAndListData: headerAndListData,
        infoData: headerData,
      }, () => {
        this.getToleAmount();
      })
    })
  }

  //获取日记账行
  getBudgetJournalLine() {
    let params = {};
    params.page = this.state.page;
    params.size = this.state.pageSize;
    this.setState({
      loading: true,
      spinLoading: true,
    })
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalLineDetil(budgetCode, params).then((response) => {
      this.setState({
        loading: false,
        spinLoading: false
      })
      let listData = response.data;
      this.setState({
        data: listData,
        total: Number(response.headers['x-total-count']),
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch((e) => {
      this.setState({
        loading: false,
        spinLoading: false
      })
      message.error(e.response.data.message);
    })

  }


  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getBudgetJournalLine();
      })
  };


  //根据attachmentOID，查询附件
  getFileByAttachmentOID = (value) => {
    let valueData = {};
    valueData.oid = value;
    budgetJournalService.getFileByAttachmentOID(valueData).then((resp) => {
      let fileList = this.state.fileList;
      fileList.addIfNotExist(resp.data)
      this.setState({
        fileList: fileList
      })
    }).catch(e => {
      message.error(`${messages('budget.key98'/*获取附件失败*/)},${e.response.data.message}`);
    })
  }

  //根据预算日记账编码查询预算日记账头行
  getDataByBudgetJournalCode = () => {
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalHeaderLine(budgetCode).then((request) => {
      let listData = request.data.list;
      let headerData = request.data.dto;
      this.getDimensionByStructureId(headerData.structureId);
      headerData.attachmentOID.map((item) => {
        this.getFileByAttachmentOID(item);
      })

      this.setState({
        headerAndListData: request.data,
        infoData: headerData,
        data: listData,
        total: listData.length
      })
    })
  };

  //根据预算表id，获得维度
  getDimensionByStructureId = (value) => {
    budgetJournalService.getDimensionByStructureId(value).then(res => {
      this.getColumnsAndDimensionHandleData(res.data)
    }).catch(e => {
      message.error(`${messages('budget.key114'/*获得维度失败*/)},${e.response.data.message}`)
    })
  };

  //根据预算表的维度.获取维度Columns
  getColumnsAndDimensionHandleData = (dimensionList) => {
    let columns = this.state.columns;
    for (let i = 0; i < dimensionList.length; i++) {
      const item = dimensionList[i];
      const priority = item.sequenceNumber;
      columns.push({
        title: `${item.dimensionName}`, dataIndex: `dimension${priority}ValueName`, width: '120px',
        render: recode => <Popover content={recode}>{recode}</Popover>
      })
    }
    this.setState({ columns }, () => {
      this.setState({ spinLoading: false })
    })
  };

  //通过
  handlePass = () => {
    message.warning(messages('budget.key131'/*数据量多时，通过缓慢，请等待*/));
    this.setState({ spinLoading: true, passLoading: true });
    const id = this.state.headerAndListData.dto.id;
    let data = [];
    data.addIfNotExist(id);
    budgetJournalService.passJournal(data).then(() => {
      message.success(messages('common.operate.success'));
      let path = this.state.budgetJournalDetailReCheckPage.url;
      this.context.router.push(path);
    }).catch(e => {
      this.setState({ spinLoading: false, passLoading: false });
      message.error(`${messages('common.operate.filed')},${e.response.data.message}`);
    })
  };

  //驳回
  handleReject = () => {
    const id = this.state.headerAndListData.dto.id;
    let data = [];
    data.addIfNotExist(id);
    this.setState({ rejectLoading: true });
    budgetJournalService.rejectJournal(data).then(() => {
      message.success(messages('common.operate.success'));
      let path = this.state.budgetJournalDetailReCheckPage.url;
      this.context.router.push(path);
    }).catch(e => {
      this.setState({ rejectLoading: false });
      message.error(`${messages('common.operate.filed')},${e.response.data.message}`);
    })
  };

  //返回列表页
  HandleReturn = () => {
    let path = this.state.budgetJournalDetailReCheckPage.url;
    this.context.router.push(path);
  };

  //返回状态
  getStatus = () => {
    const infoData = this.state.infoData;
    switch (infoData.status) {
      case 'NEW': { return <Badge status="processing" text={infoData.statusName} /> }
      case 'SUBMIT': { return <Badge status="warning" text={infoData.statusName} /> }
      case 'SUBMIT_RETURN': { return <Badge status="warning" text={infoData.statusName} /> }
      case 'REJECT': { return <Badge status="error" text={infoData.statusName} /> }
      case 'CHECKED': { return < Badge status="default" text={infoData.statusName} /> }
      case 'CHECKING': { return <Badge status="default" text={infoData.statusName} /> }
      case 'POSTED': { return <Badge status="default" text={infoData.statusName} /> }
      case 'BACKLASH_SUBMIT': { return <Badge status="default" text={infoData.statusName} /> }
      case 'BACKLASH_CHECKED': { return <Badge status="default" text={infoData.statusName} /> }
      default: { return <Badge status="default" text={infoData.statusName} /> }
    }
  };


  //获得总金额
  getAmount = () => {
    const data = this.state.data;
    let sum = 0;
    data.map(item => sum += item.functionalAmount);
    return "CNY" + " " + sum.toFixed(2);
  };

  //获取附件
  getFile = () => {
    const fileList = this.state.fileList;
    let file_arr = [];
    fileList.map((link) => {
      file_arr.push(
        <div key={link.fileURL}>
          <a href={link.fileURL} target="_blank"><Icon type="paper-clip" /> {link.fileName}</a>
        </div>
      )
    });
    return file_arr.length > 0 ? file_arr : '-';
  };

  render() {
    const { data, columns, infoData, passLoading, rejectLoading } = this.state;
    return (
      <div className="budget-journal-re-check-detail">

        <div className="base-info">
          <div className="base-info-header">
            {messages('budget.key100'/*基本信息*/)}
          </div>

          <Row className="base-info-cent" type="flex" gutter={10}>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key101'/*状态*/)}:</div>
              <div className="beep-info-text">
                {this.getStatus()}
              </div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key102'/*预算日记账编号*/)}:</div>
              <div className="beep-info-text">{infoData.journalCode ? infoData.journalCode : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key94'/*金额*/)}:</div>
              <div className="beep-info-text">
                {this.state.totalAmount}
              </div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key103'/*申请人*/)}:</div>
              <div className="beep-info-text">{infoData.employeeName ? infoData.employeeName : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key86'/*部门*/)}:</div>
              <div className="beep-info-text">{infoData.unitName ? infoData.unitName : '-'}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key104'/*创建时间*/)}:</div>
              <div className="beep-info-text">{String(infoData.createdDate).substring(0, 10)}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key105'/*预算日记账类型*/)}:</div>
              <div className="beep-info-text">{infoData.journalTypeName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key106'/*预算表*/)}:</div>
              <div className="beep-info-text">{infoData.structureName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key107'/*场景*/)}:</div>
              <div className="beep-info-text">{infoData.scenario}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key108'/*版本*/)}:</div>
              <div className="beep-info-text">{infoData.versionName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key109'/*编制期段*/)}:</div>
              <div className="beep-info-text">{infoData.periodStrategyName}</div>
            </Col>
            <Col span={8}>
              <div className="base-info-title">{messages('budget.key110'/*附件*/)}:</div>
              <div className="beep-info-text">{this.getFile()}</div>
            </Col>
          </Row>
        </div>
        <Spin spinning={this.state.spinLoading}>
          <Table columns={columns}
                 dataSource={data}
                 loading={this.state.loading}
                 bordered
                 size="middle"
                 scroll={{ x: '150%' }}
                 rowKey={recode => { return recode.id }}
                 pagination={this.state.pagination}
          />
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          <span>{messages('budget.key132'/*审批意见*/)}：&nbsp;</span><Input className="approve-opinion" />
          <Button loading={passLoading}
                  type="primary"
                  className="button-pass"
                  onClick={this.handlePass}>{messages('budget.key133'/*通过*/)}</Button>
          <Button loading={rejectLoading}
                  className="button-reject"
                  onClick={this.handleReject}>{messages('budget.key134'/*驳回*/)}</Button>
          <Button className="button-return"
                  onClick={this.HandleReturn}>{messages('budget.key111'/*返回*/)}</Button>
        </Affix>
      </div>


    )
  }

}


BudgetJournalReCheckDetail.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(BudgetJournalReCheckDetail);
